package com.oxchinx.product.service.Impl;

import com.oxchinx.product.dao.ProductCategoryRepository;
import com.oxchinx.product.dao.ProductInfoRepository;
import com.oxchinx.product.dto.CartDTO;
import com.oxchinx.product.exception.ProductException;
import com.oxchinx.product.model.ProductInfo;
import com.oxchinx.product.model.enums.ProductStatusEnum;
import com.oxchinx.product.model.enums.ResultEnum;
import com.oxchinx.product.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * Created by dell on 2018/5/21.
 */
@Service
public class ProductInfoServiceImpl implements ProductInfoService {
    @Autowired
    private ProductInfoRepository productInfoRepository;

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public List<ProductInfo> findList(List<String> productIdList) {
        return productInfoRepository.findByProductIdIn(productIdList);
    }

    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cartDTOList) {
        for(CartDTO cartDTO:cartDTOList){
            ProductInfo productInfo = productInfoRepository.findOne(cartDTO.getProductId());
            /**
             * 判断商品是否存在
             */
            if(productInfo == null){
                throw new ProductException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            Integer result = productInfo.getProductStock() - cartDTO.getProductQuantity();
            /**
             * 判断库存是否有误
             */
            if(result < 0){
                throw new ProductException(ResultEnum.PRODUCT_STOCK_ERROR);
            }

            productInfo.setProductStock(result);
            productInfoRepository.save(productInfo);
        }
    }
}
